﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text.RegularExpressions;

namespace LearnCSharp
{
	class Program
	{
		static void Main(string[] args)
		{
		
		}

	}

	public class Mp4CompressCore
	{
		public string FFProbe { get; set; } = "ffprobe.exe";
		public string FFMpeg { get; set; } = "ffmpeg.exe";
		public string Prefix { get; set; } = "new_";
		public string OutPutSiseLimit { get; set; } = "1700K";
		public int CheckDuration(string fileFullName)
		{
			int result = 0;
			Process p = new Process();
			p.StartInfo.FileName = FFProbe;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardOutput = true;
			p.StartInfo.RedirectStandardError = true;
			p.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
			{
				result = calcDuration(e.Data);
			};
			p.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
			{
				result = calcDuration(e.Data);
			};
			p.StartInfo.Arguments = fileFullName;
			p.Start();
			p.BeginErrorReadLine();
			p.BeginOutputReadLine();
			p.WaitForExit();
			return result;
		}

		public string DoCompress(string fileFullName)
		{
			Process p = new Process();
			p.StartInfo.FileName = FFMpeg;
			p.StartInfo.UseShellExecute = false;
			var file = Path.GetFileName(fileFullName);
			var path = Path.GetDirectoryName(fileFullName);
			p.StartInfo.Arguments = $"-i {fileFullName} -fs {OutPutSiseLimit} {path}\\{Prefix}{file} -y";
			p.Start();
			p.WaitForExit();
			return $"{path}\\{Prefix}{file}";
		}
		private int calcDuration(string text)
		{
			if (string.IsNullOrEmpty(text)) return 0;

			var t = Regex.Match(text, @"Duration:.*?\.");
			if (t.Success)
			{
				var rs = t.Value.Replace("Duration:", "").Replace(".", "").Trim().Split(':');
				var time = int.Parse(rs[0]) * 3600 + int.Parse(rs[1]) * 60 + int.Parse(rs[2]);
				return time;
			}
			return 0;
		}
	}
}
